#!/bin/sh
#
# parallel online
#
# 2022-11-24: Created by yike
#

# vi tasklist
# sql_file -> new_table -> new_database -> row
# GSP_PURCHASE_ORDER -> od_purchase_order -> gsp_order -> 10000
# GSP_PURCHASE_ORDER_ITEM -> od_purchase_order_item -> gsp_order -> 10000

old_host='10.0.18.4'
old_database='BPM'
old_user='system'
old_password='password'

pre_sql='alter session set current_schema = yike'

new_host='10.0.164.232'
new_user='yike'
new_password='password'

parallel=4
thread=2

function para_init() {
    tempfifo="my_temp_fifo_rigong"
    mkfifo ${tempfifo}
    exec 6<>${tempfifo}
    rm -f ${tempfifo}
    for ((i = 1; i <= ${1}; i++)); do
        echo
    done >&6
}

function para_run() {
    OLD_IFS=$IFS
    IFS=$'\n'
    i=0
    for task in $1; do
        i=$((i + 1))
        read -u6
        {
            para_stask "$task" "$i"
            echo "" >&6
        } &
    done
    IFS=$OLD_IFS
    wait
    exec 6>&-
}

# 任务函数
function para_stask() {
    sql_file=$(echo $1 | awk -F' -> ' '{print $1}')
    new_table=$(echo $1 | awk -F' -> ' '{print $2}')
    new_database=$(echo $1 | awk -F' -> ' '{print $3}')
    row=$(echo $1 | awk -F' -> ' '{print $4}')

    PRE_SQL=$pre_sql
    [ "$pre_sql" != "" ] && PRE_SQL='--pre_sql "$pre_sql"'
    printf "%s: [%02d] Doing %s\n" "$(date '+%Y-%m-%d %H:%M:%S')" "$2" "$1"
    ./oracle_mysql --online --thread $thread --ob $old_database --oh $old_host --ou $old_user --ok "$old_password" --sql ${sql_file}.txt "$PRE_SQL" \
    --tt $new_table --tb $new_database --th $new_host --tu yike --tk "$new_password" --row $row --trans 5 >trans_${new_table}_${sql_file}.log 2>&1
    printf "%s: [%02d] Done  %s\n" "$(date '+%Y-%m-%d %H:%M:%S')" "$2" "$1"
}

function main() {
    tasklist=$(cat tasklist | grep -v '^#') # 任务列表

    para_init "$parallel"
    para_run "$tasklist"
}

echo "$(date '+%Y-%m-%d %H:%M:%S'): Begin"
main
echo "$(date '+%Y-%m-%d %H:%M:%S'): Done"
